<!--
 - 用户权限审批详情页面
 - 显示申请用户信息和项目树
 - 支持为申请用户选择管理区域及角色权限
-->
<script setup lang="ts">
import { Search, Check, Close } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getUserAreaTree } from "@/plugins/ai-warning/organization/api/rdOrganizeUserStand.ts";
import { approveApply } from "@/plugins/ai-warning/organization/api/rdOrganizeUserApply.ts";
import { ResultCode } from "@/utils/ResultCode.ts";

defineOptions({ name: "organization:rdOrganizeUserApply:approve-detail" });

const props = defineProps<{
  applyData: any;
}>();

const t = useTrans().globalTrans;
const treeRef = ref();
const loading = ref(false);
const treeData = ref<any[]>([]);
const filterText = ref<string>("");
const isExpand = ref<boolean>(false); // 默认收起状态

// 审批状态
const approveStatus = ref<number>(1); // 1-通过, 2-拒绝 (用于UI显示，提交时需要转换为接口的status值：2-通过, 3-拒绝)

// 审批意见
const approveRemark = ref<string>("");

// 树配置
const defaultProps = {
  children: "children",
  label: "name",
};

// 生成唯一的节点键（因为不同层级的ID会重复）
const generateNodeKey = (
  node: any,
  level: string,
  parentKey?: string
): string => {
  if (parentKey) {
    return `${parentKey}-${level}-${node.id}`;
  }
  return `${level}-${node.id}`;
};

// 为树数据添加唯一的nodeKey
const addNodeKeys = (
  nodes: any[],
  level: string,
  parentKey?: string
): any[] => {
  return nodes.map((node) => {
    const nodeKey = generateNodeKey(node, level, parentKey);
    const newNode = {
      ...node,
      nodeKey,
      originalId: node.id, // 保存原始ID，用于提交数据
      role: node.role || 1, // 保存角色信息，默认为管理员
      level: node.type, // 使用接口返回的type字段作为level
    };

    if (node.children && node.children.length > 0) {
      // 根据当前层级确定下一层级
      let nextLevel = level;
      if (level === "zone") nextLevel = "proj_line";
      else if (level === "proj_line") nextLevel = "area";
      else if (level === "area") nextLevel = "stand";

      newNode.children = addNodeKeys(node.children, nextLevel, nodeKey);
    }

    return newNode;
  });
};

// 过滤树数据，只保留有站点的分支
const filterTreeData = (nodes: any[]): any[] => {
  return nodes
    .map((node) => {
      const newNode = { ...node };
      if (node.children && node.children.length > 0) {
        newNode.children = filterTreeData(node.children);
      }
      return newNode;
    })
    .filter((node) => {
      // 如果当前节点是站点，保留
      if (node.type === "stand") {
        return true;
      }
      // 如果当前节点有子节点，保留
      if (node.children && node.children.length > 0) {
        return true;
      }
      // 其他情况过滤掉
      return false;
    });
};

// 加载树数据
const loadTreeData = async () => {
  try {
    loading.value = true;
    const response = await getUserAreaTree(0);
    if (response.code === ResultCode.SUCCESS) {
      // 为树数据添加nodeKey并过滤
      const processedData = addNodeKeys(response.data, "zone");
      treeData.value = filterTreeData(processedData);
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 审批用户申请
const approveUserApply = async () => {
  try {
    loading.value = true;

    // 如果选择拒绝，直接调用拒绝接口
    // UI状态：approveStatus.value === 2（拒绝）-> 接口status: 3（拒绝）
    if (approveStatus.value === 2) {
      const response = await approveApply(props.applyData.id, {
        status: 3, // 接口文档：3为拒绝
        remark: approveRemark.value, // 审批意见
      });

      if (response && response.code === ResultCode.SUCCESS) {
        ElMessage.success("审批完成");
        emit("approve-success");
        return response; // 返回响应，以便父组件处理
      } else {
        ElMessage.error(response?.message || "审批失败");
        throw new Error(response?.message || "审批失败");
      }
    }

    // 如果选择通过，需要收集选中的站点数据
    // UI状态：approveStatus.value === 1（通过）-> 接口status: 2（通过）
    const selectedSites = collectSelectedAreas();

    if (selectedSites.length === 0) {
      ElMessage.warning("请至少选择一个站点");
      throw new Error("请至少选择一个站点");
    }

    const response = await approveApply(props.applyData.id, {
      status: 2, // 接口文档：2为通过
      ids: selectedSites, // 站点对象数组：[{ s: 站点id, r: 角色id }]
      remark: approveRemark.value, // 审批意见
    });

    if (response && response.code === ResultCode.SUCCESS) {
      ElMessage.success("审批完成");
      emit("approve-success");
      return response; // 返回响应，以便父组件处理
    } else {
      ElMessage.error(response?.message || "审批失败");
      throw new Error(response?.message || "审批失败");
    }
  } catch (error) {
    ElMessage.error("审批失败");
    throw error; // 抛出错误，让父组件处理
  } finally {
    loading.value = false;
  }
};

// 收集选中的站点数据（只收集 type 为 "stand" 的节点）
const collectSelectedAreas = (): any[] => {
  const sites: any[] = [];

  // 使用 el-tree 的 getCheckedNodes 方法获取选中的节点
  const checkedNodes = treeRef.value?.getCheckedNodes() || [];

  // 只收集 type 为 "stand" 的站点
  checkedNodes.forEach((node: any) => {
    if (node.type === "stand") {
      // 站点格式：{ s: 站点id, r: 角色id }
      // r: 1 表示管理员，2 表示安全员
      sites.push({
        s: node.originalId || node.id, // s 代表站点 id
        r: node.role || 1, // r 代表角色 id，默认 1（管理员）
      });
    }
  });

  return sites;
};

// 过滤树节点
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

// 监听搜索文本变化
watch(filterText, (val: string) => {
  treeRef.value?.filter(val);
});

// 切换展开/折叠
const toggleExpand = () => {
  isExpand.value = !isExpand.value;
  const nodes = treeRef.value?.store?._getAllNodes();
  nodes?.forEach((node: any) => {
    node.expanded = isExpand.value;
  });
};

// 切换站点角色
const handleRoleChange = (
  node: any,
  role: string | number | boolean | undefined
) => {
  node.role = Number(role);
};

// 角色选项
const roleOptions = [
  { label: "管理员", value: 1 },
  { label: "安全员", value: 2 },
];

// 定义事件
const emit = defineEmits<{
  "approve-success": [];
}>();

// 页面加载时获取数据
onMounted(() => {
  loadTreeData();
});

// 暴露审批方法给父组件调用
defineExpose({
  approveUserApply,
});
</script>

<template>
  <div class="approve-detail" v-loading="loading">
    <!-- 顶部信息栏 - 紧凑显示 -->
    <div class="info-header">
      <div class="applicant-info">
        <div class="info-item">
          <span class="label">申请人：</span>
          <span class="value">{{ applyData.name || "未知" }}</span>
        </div>
        <div class="info-item">
          <span class="label">电话：</span>
          <span class="value">{{ applyData.phone || "未知" }}</span>
        </div>
        <div class="info-item">
          <span class="label">申请范围：</span>
          <el-tag
            :type="
              applyData.area === 1
                ? 'info'
                : applyData.area === 2
                ? 'warning'
                : 'success'
            "
            size="small"
          >
            {{
              applyData.area === 1
                ? "项目"
                : applyData.area === 2
                ? "工区"
                : "站点"
            }}
          </el-tag>
        </div>
        <div class="info-item">
          <span class="label">申请时间：</span>
          <span class="value">{{ applyData.created_at || "未知" }}</span>
        </div>
        <div class="info-item">
          <span class="label">状态：</span>
          <el-tag type="warning" size="small">待审批</el-tag>
        </div>
      </div>
    </div>

    <!-- 审批决定和审批意见 -->
    <div class="approve-section">
      <!-- 审批决定 -->
      <div class="approve-decision-row">
        <span class="approve-label">审批决定：</span>
        <el-radio-group v-model="approveStatus" class="approve-radio-group">
          <el-radio-button :value="1" class="approve-pass">
            <el-icon><Check /></el-icon>
            审批通过
          </el-radio-button>
          <el-radio-button :value="2" class="approve-reject">
            <el-icon><Close /></el-icon>
            拒绝申请
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 审批意见 -->
      <div class="approve-remark-row">
        <span class="remark-label">审批意见：</span>
        <el-input
          v-model="approveRemark"
          type="textarea"
          :rows="3"
          placeholder="请输入审批意见..."
          class="remark-input"
        />
      </div>
    </div>

    <!-- 项目树选择 - 只有选择通过时才显示 -->
    <div v-if="approveStatus === 1" class="tree-section">
      <div class="tree-header">
        <span class="tree-title">为申请人选择管理区域及角色权限</span>
      </div>

      <div class="tree-container">
        <!-- 搜索和操作栏 -->
        <div class="tree-toolbar">
          <el-input
            v-model="filterText"
            placeholder="搜索区域名称"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button @click="toggleExpand" size="small">
            {{ isExpand ? "收起全部" : "展开全部" }}
          </el-button>
        </div>

        <!-- 树形控件 -->
        <div class="tree-scroll-container">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            show-checkbox
            node-key="nodeKey"
            :default-expand-all="false"
            class="tree-content"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <span class="node-label">{{ data.name }}</span>
                <!-- 只有站点才显示角色选择 -->
                <div
                  v-if="data.type === 'stand'"
                  class="node-actions"
                  @click.stop
                >
                  <el-radio-group
                    v-model="data.role"
                    @change="(val) => handleRoleChange(data, val)"
                    size="small"
                  >
                    <el-radio-button
                      v-for="option in roleOptions"
                      :key="option.value"
                      :value="option.value"
                      size="small"
                    >
                      {{ option.label }}
                    </el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.approve-detail {
  // 顶部信息栏样式
  .info-header {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 12px 16px;
    margin-bottom: 16px;

    .applicant-info {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      margin-bottom: 12px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 4px;

        .label {
          font-size: 13px;
          color: #666;
          font-weight: 500;
        }

        .value {
          font-size: 13px;
          color: #333;
        }
      }
    }

    // 审批区域样式
    .approve-section {
      margin: 20px 0;
      padding: 16px 20px;
      background: #f8fafc;
      border-radius: 8px;
      border: 1px solid #e2e8f0;

      // 审批决定行
      .approve-decision-row {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 16px;

        .approve-label {
          font-size: 14px;
          font-weight: 500;
          color: #374151;
          min-width: 80px;
        }

        .approve-radio-group {
          display: flex;
          gap: 12px;

          :deep(.el-radio-button) {
            .el-radio-button__inner {
              display: flex;
              align-items: center;
              gap: 6px;
              padding: 8px 16px;
              font-size: 14px;
              border-radius: 6px;
              transition: all 0.2s ease;

              &:hover {
                transform: translateY(-1px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              }
            }

            &.is-active {
              .el-radio-button__inner {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
              }
            }
          }

          .approve-pass {
            :deep(.el-radio-button__inner) {
              background: #10b981;
              color: white;
              border-color: #10b981;

              &:hover {
                background: #059669;
                border-color: #059669;
              }
            }

            &.is-active :deep(.el-radio-button__inner) {
              background: #047857;
              border-color: #047857;
            }
          }

          .approve-reject {
            :deep(.el-radio-button__inner) {
              background: #ef4444;
              color: white;
              border-color: #ef4444;

              &:hover {
                background: #dc2626;
                border-color: #dc2626;
              }
            }

            &.is-active :deep(.el-radio-button__inner) {
              background: #b91c1c;
              border-color: #b91c1c;
            }
          }
        }
      }

      // 审批意见行
      .approve-remark-row {
        display: flex;
        align-items: flex-start;
        gap: 16px;

        .remark-label {
          font-size: 14px;
          font-weight: 500;
          color: #374151;
          min-width: 80px;
          margin-top: 8px;
        }

        .remark-input {
          flex: 1;

          :deep(.el-textarea__inner) {
            border-radius: 6px;
            border: 1px solid #d1d5db;
            font-size: 14px;
            line-height: 1.5;

            &:focus {
              border-color: #3b82f6;
              box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
            }
          }
        }
      }
    }
  }

  // 树形区域样式
  .tree-section {
    .tree-header {
      margin-bottom: 12px;

      .tree-title {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
    }

    .tree-container {
      .tree-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        gap: 12px;

        .search-input {
          flex: 1;
          max-width: 300px;
        }
      }

      .tree-scroll-container {
        height: 350px; // 增加树形区域高度
        overflow-y: auto;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 8px;
        background: #fff;
      }

      .tree-content {
        .tree-node {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 4px 0;

          .node-label {
            flex: 1;
            font-size: 13px;
          }

          .node-actions {
            margin-left: 12px;

            :deep(.el-radio-group) {
              .el-radio-button {
                margin-right: 4px;

                &:last-child {
                  margin-right: 0;
                }

                .el-radio-button__inner {
                  padding: 4px 12px;
                  font-size: 12px;
                  border-radius: 4px;
                  transition: all 0.2s ease;

                  &:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                  }
                }

                &.is-active {
                  .el-radio-button__inner {
                    background: #409eff;
                    color: white;
                    border-color: #409eff;
                    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
                  }
                }

                &:not(.is-active) {
                  .el-radio-button__inner {
                    background: #f5f7fa;
                    color: #606266;
                    border-color: #dcdfe6;

                    &:hover {
                      background: #ecf5ff;
                      color: #409eff;
                      border-color: #c6e2ff;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
